package com.vip.mvc.akka;

import akka.dispatch.Futures;
import akka.dispatch.Mapper;
import com.vip.mvc.dispacher.MyDispacher;
import scala.concurrent.Future;
import scala.concurrent.Promise;

import java.util.function.Consumer;
import java.util.function.Function;

/**
 * Created by vipshop on 17/2/20.
 */
public class Promises {
    public static <U> Future<Object> flatMap (U reqObj,Function<U,Object> function){
        Promise<U> promise = Futures.promise();
        Future<U> future = promise.future();
        promise.success(reqObj);

        Future<Object> respFuture = future.flatMap(new Mapper<U, Future<Object>>() {
            public Future<Object> checkedApply(U request) throws Throwable {
                Object returnObj = function.apply(request);
                return toPromise(returnObj);
            }
        }, MyDispacher.getInstance().getActorSystem().dispatcher());
        return respFuture;
    }

    public static <U> void flatMap (U reqObj,Consumer<U> consumer){
        Promise<U> promise = Futures.promise();
        Future<U> future = promise.future();
        promise.success(reqObj);

        future.flatMap(new Mapper<U, Future<Object>>() {
            public Future<Object> checkedApply(U request) throws Throwable {
                consumer.accept(request);
                return null;
            }
        }, MyDispacher.getInstance().getActorSystem().dispatcher());
    }

    private static Future<Object> toPromise(Object obj) {
        Promise<Object> cf = Futures.promise();
        cf.success(obj);
        return cf.future();
    }
}
